﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;

namespace Baddies.Utils
{
    /// <summary>
    /// Custom serializer for the SharedResourceList class.
    /// Use it to serialize all items as references.
    /// </summary>
    /// <typeparam name="T">Type of object in the SharedResourceList.</typeparam>
    [ContentTypeSerializer]
    public class SharedResourceListSerializer<T> : ContentTypeSerializer<SharedResourceList<T>>
    {
        /// <summary>
        /// Custom format for the items.
        /// </summary>
        private static ContentSerializerAttribute itemFormat = new ContentSerializerAttribute()
        {
            ElementName = "Item"
        };

        /// <summary>
        /// Serializes the SharedResourceList.
        /// </summary>
        /// <param name="output">Writer to serialize to.</param>
        /// <param name="value">List to serialize.</param>
        /// <param name="format">Format options for serialization.</param>
        protected override void Serialize(
            IntermediateWriter output,                                          
            SharedResourceList<T> value,                                          
            ContentSerializerAttribute format)
        {
            foreach (T item in value)
            {
                output.WriteSharedResource(item, itemFormat);
            }
        }

        /// <summary>
        /// Deserializes the SharedResourceList.
        /// </summary>
        /// <param name="input">Reader with the xml data.</param>
        /// <param name="format">Format options of the data.</param>
        /// <param name="existingInstance">SharedResourceList where we put the deserialized data.</param>
        /// <returns>The deserialized SharedResourceList.</returns>
        protected override SharedResourceList<T> Deserialize(
            IntermediateReader input,
            ContentSerializerAttribute format,
            SharedResourceList<T> existingInstance)
        {
            if (existingInstance == null)
            {
                existingInstance = new SharedResourceList<T>();
            }

            while (input.MoveToElement(itemFormat.ElementName))
            {
                input.ReadSharedResource(
                    itemFormat,
                    (T item) => existingInstance.Add(item));
            }

            return existingInstance;
        }
    }
}
